package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.bo.SpuBO;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.SpecParam;
import com.leyou.item.pojo.Spu;
import com.leyou.item.pojo.SpuDetail;
import com.leyou.search.client.BrandClient;
import com.leyou.search.client.CategoryClient;
import com.leyou.search.client.GoodsClient;
import com.leyou.search.client.SpecificationClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.respository.GoodsRepository;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: taft
 * @Date: 2018-10-18 11:33
 */
@Service
public class GoodsService {

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private BrandClient brandClient;


    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private SpecificationClient specificationClient;

    /**
     * 要根据spu来构建一个goods对象，最终使用goodsRepository来保存这个goods对象
     *
     * @param spuBO
     */
    public Goods buildGoods(SpuBO spuBO) {
        Goods goods = new Goods();

        BeanUtils.copyProperties(spuBO, goods);

        //缺 all 所有需要被搜索的信息，包含标题，分类，甚至品牌

        StringBuilder all = new StringBuilder();

        all.append(spuBO.getTitle());

        List<String> list = this.categoryClient.queryNameByIds(Arrays.asList(spuBO.getCid1(), spuBO.getCid2(), spuBO.getCid3()));

        all.append(StringUtils.join(list, " "));//手机 手机通讯 手机


        all.append(this.brandClient.queryBrandById(spuBO.getBrandId()).getName());

        //把all的值赋值给goods
        goods.setAll(all.toString());


        //缺 sku  调用client去根据spuid查询sku
        List<Sku> skus = this.goodsClient.querySkuBySpuId(spuBO.getId());

        if (null==skus){
            return null;
        }

        //TODO 根据skuId查询对应的stock然后遍历赋值

        //缺 price  使用sku来构造precice
        List<Long> preces = new ArrayList<>();

        skus.forEach(sku -> preces.add(sku.getPrice()));


        goods.setSkus(JsonUtils.serialize(skus));

        //把根据sku建立的价格几个加到goods中
        goods.setPrice(preces);

        //缺specs

        //通过spuid获取spu对应的souDetail
        SpuDetail spuDetail = this.goodsClient.querySpuDetailById(spuBO.getId());

        //查询出所有可以搜索的字段信息
        List<SpecParam> specParams = this.specificationClient.querySpecParam(null, spuBO.getCid3(), true, null);

        //从spuDetail中获取当前spu所有的规格参数
        Map<Long, String> genericSpecMap = JsonUtils.parseMap(spuDetail.getGenericSpec(), Long.class, String.class);

        Map<Long, List<String>> specialSpecMap = JsonUtils.nativeRead(spuDetail.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
        });


        //处理规格参数显示问题，默认显示id+值，处理后显示id对应的名称+值
        Map<String, Object> specs = new HashMap<>();  //操作系统：android,颜色:[红色，绿色，蓝色]

        //迭代所有可以搜索的字段
        for (SpecParam specParam : specParams) {
            //获取当前可搜索字段的id
            Long id = specParam.getId();

            //获取可搜索字段的名称
            String name = specParam.getName();

            Object value = null;

            //判断可搜索字段是通用属性还是特有属性
            if (specParam.getGeneric()) {
                //从通用规格参数中取值
                value = genericSpecMap.get(id);

                //如果这个值为数值类型那么要去选择他的区间
                if (specParam.getNumeric()) {
                    value = chooseSegment(value + "", specParam);
                }
            } else {
                value = specialSpecMap.get(id);
            }

            if (null == value) {
                value = "其他";
            }
            specs.put(name, value);

        }


        goods.setSpecs(specs);


        return goods;
    }


    private String chooseSegment(String value, SpecParam p) {
        double val = NumberUtils.toDouble(value);
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = NumberUtils.toDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = NumberUtils.toDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    public void createIndex(Long id){
        Spu spu = this.goodsClient.querySpuById(id);
        SpuBO spuBo = new SpuBO();
        BeanUtils.copyProperties(spu,spuBo);
        Goods goods = this.buildGoods(spuBo);
        if (goods != null) {
            this.goodsRepository.save(goods);
        }

    }

    public void deleteIndex(Long id) {
        this.goodsRepository.deleteById(id);
    }


}
